package com.mianyang.zhangsan.auth.exception;

import com.mianyang.zhangsan.common.base.R;
import com.mianyang.zhangsan.common.util.JsonUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 授权失败异常处理
 * @author jiangjr
 * @date 2022-10-23
 */
@Component
public class AccessDeniedHandle implements AccessDeniedHandler {
    // TODO 将不同异常分类处理 -登录过期异常，-没有对应权限异常，-没有登录异常等等

    /**
     * 授权失败异常处理
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpStatus.FORBIDDEN.value());
        R result = new R(HttpStatus.FORBIDDEN.value(), "你暂未拥有此权限，请联系管理员.");
        response.getWriter().write(JsonUtils.toString(result));
    }
}
